<template>
  <div class="xmind-list-recents">
    <CardGrid
      v-show="grid === 'card'"
      :mindList="mindList"
      :skeletonLoading=skeletonLoading
      @refresh-page="queryRecentMindList"
      @update-collect-status="updateCollectStatus"
      @mind-click="handleMindClick" />

    <ListGrid
      v-show="grid === 'list'"
      :mindList="mindList"
      :skeletonLoading="skeletonLoading"
      @refresh-page="queryRecentMindList"
      @update-collect-status="updateCollectStatus"
      @mind-click="handleMindClick" />
  </div>
</template>

<script setup lang="ts">
import { ref, defineProps, PropType, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { dayjs } from 'element-plus'
import mitter from '@/mitt'
import { apiGetMindList } from '@/apis/work'
import type { Mind } from '@/types'
import CardGrid from '@/pages/home/components/CardGrid.vue'
import ListGrid from '@/pages/home/components/ListGrid.vue'
defineProps({
  grid: {
    type: String as PropType<'card' | 'list'>,
    default: 'card'
  }
})
const router = useRouter()

const mindList = ref<Mind[]>([])

const searchKeywords = ref('')

const skeletonLoading = ref(false)
/**
 * 最近导图列表查询
 */
const queryRecentMindList = async () => {
  skeletonLoading.value = true
  try {
    const data = await apiGetMindList<Mind[]>(
      {
        name: searchKeywords.value,
        startUpdateTime: dayjs().subtract(3, 'day').format('YYYY-MM-DD HH:mm:ss'),
        endUpdateTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
      }
    )
    mindList.value = data
    skeletonLoading.value = false
  } catch (error) {
    skeletonLoading.value = false
  }
}
queryRecentMindList()

/**
 * 静态更新导图的收藏状态
 * @param mindId
 * @param status
 */
const updateCollectStatus = (mindId: string, status: boolean) => {
  const mind = mindList.value.find(m => m.id === mindId)
  if (mind) {
    mind.isCollected = status ? 1 : 0
  }
}

const handleMindClick = (mindItem: Mind) => {
  router.push(`/mind-map/${mindItem.id}`)
}

mitter.on('search-mind-list', function (keywords?: any) {
  searchKeywords.value = keywords
  queryRecentMindList()
})

onBeforeUnmount(() => {
  mitter.off('search-mind-list')
})
</script>

<style lang="scss" scoped></style>
